package com.xiaoyu.base.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.xiaoyu.base.app.AppContext;
import com.xiaoyu.base.image.ImageUrlManager;
import com.xiaoyu.base.net.OkHttpDownloader;
import in.srain.cube.util.UriUtil;
import com.xiaoyu.base.app.GlobalUI;

import java.io.File;

import in.srain.cube.util.CLog;
import in.srain.cube.util.FilenameUtil;

public class VideoUtil {

    public static final String TAG = VideoUtil.class.getSimpleName();
    private static final String VIDEO_PATH_NAME_PREFIX = Environment.getExternalStorageDirectory().toString() + File.separator + "CPVideo";

    public static int getVideoHeight(Context context, String path) {
        File file = new File(path);
        if (file.exists()) {
            return getVideoHeight(context, file);
        }
        return 0;
    }

    public static int getVideoHeight(Context context, File file) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(context, Uri.fromFile(file));
        Bitmap bitmap = retriever.getFrameAtTime();
        int height = bitmap.getHeight();
        retriever.release();
        return height;
    }

    public static int getVideoWidth(Context context, String path) {
        File file = new File(path);
        if (file.exists()) {
            return getVideoWidth(context, file);
        }
        return 0;
    }

    public static int getVideoWidth(Context context, File file) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(context, Uri.fromFile(file));
        Bitmap bitmap = retriever.getFrameAtTime();
        int width = bitmap.getWidth();
        retriever.release();
        return width;
    }

    public static long getVideoDuration(Context context, String path) {
        File file = new File(path);
        if (file.exists()) {
            return getMediaDuration(context, file);
        }
        return 0;
    }

    public static long getAudioDurationForSecond(Context context, String path) {
        File file = new File(path);
        if (file.exists()) {
            return getMediaDuration(context, file) / 1000;
        }
        return 0;
    }

    public static long getDurationForSecond(Context context, String path) {
        File file = new File(path);
        if (file.exists()) {
            return getMediaDuration(context, file) / 1000;
        }
        return 0;
    }

    public static long getSizeForKB(String path) {
        File file = new File(path);
        if (file.exists()) {
            return new File(path).length() / 1024;
        }
        return 0;
    }

    public static long getMediaDuration(Context context, File file) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        long timeInMilliSec;
        try {
            retriever.setDataSource(context, Uri.fromFile(file));
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            timeInMilliSec = Long.parseLong(time);
        } catch (Throwable e) {
            e.printStackTrace();
            timeInMilliSec = 0;
        } finally {
            retriever.release();
        }
        return timeInMilliSec;
    }

    public static void saveVideo(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        String extension = FilenameUtil.getExtension(url);
        String filePath = String.format("%s%scp_%s.%s", VIDEO_PATH_NAME_PREFIX, File.separator, System.currentTimeMillis(), extension);
        File file = new File(filePath);

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        String tempUrl = url;
        if (tempUrl.contains(ImageUrlManager.NEWSNS_YIZHOUCP_IMAGE_DOMAIN) && tempUrl.contains(ImageUrlManager.HTTPS)) {
            tempUrl = tempUrl.replace(ImageUrlManager.HTTPS, ImageUrlManager.HTTP);
        }
        OkHttpDownloader downloader = new OkHttpDownloader(tempUrl, file.getAbsolutePath());
        downloader.setDownloadStatusListener(new OkHttpDownloader.DownloadStatusListener() {
            @Override
            public void onStart() {
                CLog.i(TAG, "onStart() url=%s, path:%s", url, file.getAbsoluteFile());
            }

            @Override
            public void onSuccess() {
                CLog.i(TAG, "onSuccess() exits=%s", file.exists());
                if (!file.exists()) {
                    GlobalUI.getInstance().showToast("保存失败：文件未找到");
                } else {
                    String mimeType = UriUtil.getMimeType(AppContext.getContext(), file);
                    String[] mimeTypes = new String[]{mimeType};
                    MediaScannerConnection.scanFile(AppContext.getContext(), new String[]{file.getAbsolutePath()}, mimeTypes, (path, uri) ->
                            CLog.i(TAG, "Scanned path:%s, uri=%s", path, uri));
                    GlobalUI.getInstance().showToast("保存成功 " + file.getPath());
                }
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
                GlobalUI.getInstance().showToast("保存失败：存储权限可能未赋予，或网络错误");
            }

            @Override
            public void onEnd() {
                CLog.e(TAG, "onEnd()");
            }

            @Override
            public void onCancel() {
                CLog.e(TAG, "onCancel()");
            }
        });
        downloader.download();
    }
}
